import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { Tag } from './entities/tag.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(Tag) private readonly tagRepository: Repository<Tag>,
  ) {}

  async create(createTagDto: CreateTagDto) {
    const { label } = createTagDto;
    const hasTag = await this.tagRepository.findOneBy({ label });
    if (hasTag) {
      throw new BadRequestException('标签已存在');
    }
    return this.tagRepository.save(createTagDto);
  }

  async findAll() {
    return await this.tagRepository.find();
  }

  async findOne(id: number) {
    const tag = await this.tagRepository.findOneBy({ id });
    if (!tag) {
      throw new BadRequestException('标签不存在');
    }
    return tag;
  }

  async update(id: number, updateTagDto: UpdateTagDto) {
    if (!id) {
      throw new BadRequestException('id不能为空');
    }
    const oldTag = await this.tagRepository.findOneBy({ id });
    if (!oldTag) {
      throw new BadRequestException('标签不存在');
    }

    return await this.tagRepository.save({ id, ...updateTagDto });
  }

  async remove(id: number) {
    if (!id) {
      throw new BadRequestException('id不能为空');
    }
    const oldTag = await this.tagRepository.findOneBy({ id });
    if (!oldTag) {
      throw new BadRequestException('标签不存在');
    }
    oldTag.isDelete = true;
    return await this.tagRepository.save(oldTag);
  }
}
